<template>
  <div>
    <!-- 上传文件的xlsx -->
    <input
      id="table1"
      type="file"
      accept=".xlsx, .xls"
      style="display:none"
      @change="handleFileUpload"
    />
    <el-row>
      <el-col>
        <span style="marginRight:10px">已择{{ multipleSelection.length }}条</span>
        <el-button
          :disabled="!multipleSelection.length"
          type="danger" 
          @click="handeBtn()"
        >批量删除</el-button>
        <el-button type="primary" @click="exportData">导出</el-button>
        <el-button type="primary" @click="clickBtn">导入</el-button>
      </el-col>
    </el-row>

    <el-table
      @selection-change="handleSelectionChange"
      v-loading="loading"
      :data="tableData"
      border
      :row-key="row => row._id"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="vpnIp" label="ip" :showOverflowTooltip="true" />
      <el-table-column prop="vpnLink" label="链接" :showOverflowTooltip="true" />
      <el-table-column prop="vpnPasswd" label="密码" /> 
      <el-table-column prop="vpnPort" label="端口号" />
      <el-table-column prop="vpnType" label="类型" />
      <el-table-column prop="vpnUsername" label="用户名" /> 
      <el-table-column prop="genTimeStr" label="生成时间" :showOverflowTooltip="true" />
      <el-table-column prop="status" label="状态"/>  
      <el-table-column prop="useCount" label="使用次数" :showOverflowTooltip="true" />

      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-link type="danger" @click="handleDel(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import axios from "axios";
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      // 不做分页
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  created() {
    this.initdata();
  },
  methods: {
    initdata() {
      this.loading = true;
      this.$http
        .get(`/api/cloud_data/vpnv2/list`)
        .then(res => {
          if (res.success) {
            this.tableData = res.data;
            this.loading = false;
          } else {
            this.$error(res.msg);
            this.loading = false;
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    // 删除
    handleDel(row) {
      this.$confirm("确定删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.delete([row._id])
        this.initdata();
      }); 

    },
    // 批量删除
    handeBtn() {
      this.$confirm("确定批量删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => { 
        this.delete(this.multipleSelection)
        this.initdata();
      }); 
    },
    // 统一删除接口
    delete(ids) { 
      this.$http
        .post(`/api/cloud_data/vpnv2/delete`,ids)
        .then(res => {
          if (res.success) {
            this.$success("删除成功");
          } else {
            this.$error(res.msg);
          }
        }) 
    },
    // 解析导入的表格
    handleFileUpload(event) {
      console.log(event.target);
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = e => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        // 在控制台打印解析后的数组
        console.log("rows", jsonData);
        this.$http.post(`/api/cloud_data/vpnv2/upload`, jsonData).then(res => {
          if (res.success) {
            this.$success("导入成功");
          } else {
            this.$error(res.msg);
          }
        });
      };

      reader.readAsArrayBuffer(file);
    },
    clickBtn() {
      const inp = document.getElementById("table1");
      inp.click();
    },
    // 导出
    exportData() {
      axios({
        url: `/api/cloud_data/vpnv2/export`,
        method: "GET",
        responseType: "blob"
      })
        .then(response => {
          // 处理文件流响应
          const blob = new Blob([response], {
            type: "application/vnd.ms-excel"
          });
          const url = URL.createObjectURL(blob);
          // 创建一个下载链接，让用户下载文件
          const link = document.createElement("a");
          link.href = url;
          link.click();
          URL.revokeObjectURL(url);
        })
        .catch(err => {
          this.loading = false;
        });
    },
    // 多选
    handleSelectionChange(val) {
      console.log("val", val);
      if (val && val.length) {
        this.multipleSelection = val.map(v => {
          return v._id 
        });
        return;
      }
      this.multipleSelection = [];
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.initdata();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initdata();
    }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  padding: 20px 0 0;
}

.el-row {
  padding: 10px 0;
}
</style>
